<script setup lang="ts">
import { reactive, ref, onMounted, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
// @ts-ignore
import { ReadClients, WriteClients } from '@/Urls/AxiosHelper'

const router = useRouter()
const route = useRoute()

const props = defineProps<{ id?: number | string, originPage?: 'list' | 'detail' }>()
const id = computed(() => props.id || route.query.id)
const originPage = computed(() => props.originPage || route.query.origin || 'list')

const readClient = ReadClients[3]
const writeClient = WriteClients[3]

const formRef = ref()
const loading = ref(false)
const form = reactive({
  productCode: '',
  autoCode: false,
  productName: '',
  unit: '',
  spec: '',
  productType: '',
  productAttr: '',
  productClass: '',
  status: true,
  validPeriod: undefined as number | undefined,
  warnAdvanceDays: undefined as number | undefined,
  warnEnable: true,
  stockUpper: undefined as number | undefined,
  stockLower: undefined as number | undefined,
  purchasePrice: undefined as number | undefined,
  salePrice: undefined as number | undefined,
  remark: '',
})

const rules = {
  productCode: [{ required: true, message: '请输入产品编码', trigger: 'blur' }],
  productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
}

const unitOptions = ['件','个','箱','台','米']
const typeOptions = ['半成品','成品','其他']
const attrOptions = ['自制','委外','外购','其他']
const classOptions = ['A类','B类','C类']

// 上传相关
const imageUrl = ref<string>('')
const attachmentUrl = ref<string>('')
const attachmentName = ref<string>('')

async function fetchDetail(){
  if(!id.value) return
  loading.value = true
  try{
    const res = await readClient.get('/productread/api/Product/GetProductById', { params:{ Id: id.value } })
    const payload = res?.data
    const data = payload?.data || payload || {}
    
    // 反填表单数据
    form.productCode = data.productNumber || ''
    form.productName = data.productName || ''
    form.spec = data.specificationModel || ''
    form.unit = data.unit || ''
    form.productType = data.productType || ''
    form.productAttr = data.productAttribute || ''
    form.productClass = data.productClassification || ''
    form.status = data.activationStatus === true || data.activationStatus === 1 || data.activationStatus === 'true'
    form.validPeriod = data.validDate || undefined
    form.warnAdvanceDays = data.alarmDays || undefined
    form.stockUpper = data.maximumInventoryLevel || undefined
    form.stockLower = data.minimumInventoryLevel || undefined
    form.purchasePrice = data.purchasePrice || undefined
    form.salePrice = data.salesPrice || undefined
    form.remark = data.remarks || ''
    
    // 设置图片和附件
    imageUrl.value = data.image || ''
    attachmentUrl.value = data.attachment || ''
    attachmentName.value = data.attachmentName || '文件'
  }catch{
    ElMessage.error('获取产品信息失败')
  }finally{
    loading.value = false
  }
}

async function handleSave(){
  // @ts-ignore
  formRef.value?.validate(async (ok:boolean)=>{
    if(!ok) return
    try{
      const payload = {
        id: Number(props.id), // 确保id为数字类型
        productNumber: form.productCode,
        productName: form.productName,
        specificationModel: form.spec,
        unit: form.unit,
        productType: form.productType,
        productAttribute: form.productAttr,
        productClassification: form.productClass,
        activationStatus: form.status,
        validDate: form.validPeriod ?? 0,
        alarmDays: form.warnAdvanceDays ?? 0,
        maximumInventoryLevel: form.stockUpper ?? 0,
        minimumInventoryLevel: form.stockLower ?? 0,
        purchasePrice: form.purchasePrice ?? 0,
        salesPrice: form.salePrice ?? 0,
        remarks: form.remark || '',
        image: imageUrl.value,
        attachment: attachmentUrl.value,
      }
      const res = await writeClient.post('/productwrite/api/Product/UpdateProduct', payload)
      if(res && (res.status===200 || res?.data?.code===200 || res?.data?.success)){
        ElMessage.success('保存成功')
        const targetRoute = originPage.value === 'detail' ? 'ProductDetail' : 'ProductInfo'
        router.push({ name: targetRoute, query: originPage.value === 'detail' ? { id: id.value } : {} })
      }else{
        throw new Error(res?.data?.message || '保存失败')
      }
    }catch(err:any){
      ElMessage.error(err?.response?.data?.message || err?.message || '保存失败')
    }
  })
}

function handleCancel(){ 
  const targetRoute = originPage.value === 'detail' ? 'ProductDetail' : 'ProductInfo'
  router.push({ name: targetRoute, query: originPage.value === 'detail' ? { id: id.value } : {} })
}

async function uploadImage(option:any){
  try{
    const fd = new FormData()
    fd.append('file', option.file)
    const res = await writeClient.post('/productwrite/api/Upload/UploadImg', fd, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    const url = res?.data?.data || ''
    imageUrl.value = url
    option?.onSuccess && option.onSuccess(res.data)
  }catch(err:any){
    option?.onError && option.onError(err)
    ElMessage.error(err?.response?.data?.message || err?.message || '图片上传失败')
  }
}

async function uploadAttachment(option:any){
  try{
    const fd = new FormData()
    fd.append('file', option.file)
    const res = await writeClient.post('/productwrite/api/Upload/UploadCompanyFile', fd, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    const url = res?.data?.data || ''
    attachmentUrl.value = url
    attachmentName.value = option.file?.name || '文件'
    option?.onSuccess && option.onSuccess(res.data)
  }catch(err:any){
    option?.onError && option.onError(err)
    ElMessage.error(err?.response?.data?.message || err?.message || '文件上传失败')
  }
}

// 系统编号开关：开启即生成 GUID 填充产品编码
function generateGuid(){
  const s = '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c: string) =>
    (Number(c) ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> Number(c) / 4).toString(16)
  )
  return s
}

watch(()=>form.autoCode, (v)=>{
  if(v){
    form.productCode = generateGuid()
  }
})

onMounted(fetchDetail)
watch(()=>id.value, fetchDetail)
</script>

<template>
  <div class="edit-wrap" v-loading="loading">
    <!-- 顶部：基础信息卡片 -->
    <el-card class="top-card">
      <template #header>
        <div class="header-row">
          <div class="title">编辑产品</div>
          <div class="spacer"></div>
        </div>
      </template>

      <div class="section-title">基础信息</div>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="96px" class="base-form">
        <div class="grid">
          <div class="col">
            <el-form-item label="产品编码" prop="productCode">
              <div class="inline">
                <el-input v-model="form.productCode" placeholder="请输入" style="width:260px" />
                <div class="gap-12"></div>
                <span class="muted">系统编号</span>
                <el-switch v-model="form.autoCode" inline-prompt />
              </div>
            </el-form-item>

            <el-form-item label="规格型号">
              <el-input v-model="form.spec" placeholder="请输入" />
            </el-form-item>

            <el-form-item label="产品类型">
              <el-select v-model="form.productType" placeholder="选择产品类型">
                <el-option v-for="o in typeOptions" :key="o" :label="o" :value="o" />
              </el-select>
            </el-form-item>

            <el-form-item label="产品分类">
              <el-select v-model="form.productClass" placeholder="选择产品分类">
                <el-option v-for="o in classOptions" :key="o" :label="o" :value="o" />
              </el-select>
            </el-form-item>

            <el-form-item label="有效期">
              <div class="inline">
                <el-input-number v-model="form.validPeriod" :min="0" :max="99999" />
                <div class="gap-8"></div>
                <span class="muted">天</span>
                <div class="gap-24"></div>
                <el-checkbox v-model="form.warnEnable" />
              </div>
            </el-form-item>

            <el-form-item label="库存上限">
              <el-input-number v-model="form.stockUpper" :min="0" />
            </el-form-item>

            <el-form-item label="采购价格">
              <el-input-number v-model="form.purchasePrice" :precision="2" :step="0.1" :min="0" />
            </el-form-item>

            <el-form-item label="备注" class="remark-item">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入" />
            </el-form-item>
          </div>

          <div class="col">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入" />
            </el-form-item>

            <el-form-item label="单位">
              <el-select v-model="form.unit" placeholder="请选择单位">
                <el-option v-for="o in unitOptions" :key="o" :label="o" :value="o" />
              </el-select>
            </el-form-item>

            <el-form-item label="产品属性">
              <el-select v-model="form.productAttr" placeholder="请选择产品属性">
                <el-option v-for="o in attrOptions" :key="o" :label="o" :value="o" />
              </el-select>
            </el-form-item>

            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="true">启用</el-radio>
                <el-radio :label="false">禁用</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="报警天数">
              <div class="inline">
                <span class="muted">提前</span>
                <div class="gap-8"></div>
                <el-input-number v-model="form.warnAdvanceDays" :min="0" :max="99999" />
                <div class="gap-8"></div>
                <span class="muted">天报警</span>
              </div>
            </el-form-item>

            <el-form-item label="库存下限">
              <el-input-number v-model="form.stockLower" :min="0" />
            </el-form-item>

            <el-form-item label="销售价格">
              <el-input-number v-model="form.salePrice" :precision="2" :step="0.1" :min="0" />
            </el-form-item>
          </div>
        </div>
      </el-form>
    </el-card>

    <!-- 图片模块 -->
    <el-card class="section-card">
      <template #header>
        <div class="section-title">图片</div>
      </template>
      <div class="image-row">
        <div class="left">
          <el-upload :http-request="uploadImage" :show-file-list="false" accept="image/*">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </div>
        <div class="right">
          <el-image v-if="imageUrl" :src="imageUrl" fit="contain" style="width: 240px; height: 160px; border:1px dashed #e5e7eb; border-radius:6px;" />
          <div v-else class="img-empty">暂无图片</div>
        </div>
      </div>
    </el-card>

    <!-- 附件模块 -->
    <el-card class="section-card">
      <template #header>
        <div class="section-title">附件</div>
      </template>
      <el-upload drag :http-request="uploadAttachment" :show-file-list="false" class="attach-drag">
        <i class="el-icon--upload"></i>
        <div class="el-upload__text">点击或将文件拖到此区域上传</div>
        <template #tip>
          <div class="el-upload__tip">支持 docx, xls, PDF, rar, zip, PNG, JPG 等类型的文件</div>
        </template>
      </el-upload>
      <div v-if="attachmentUrl" class="file-line">
        <el-link :href="attachmentUrl" target="_blank" type="primary" underline="hover">{{ attachmentName || '下载附件' }}</el-link>
      </div>
    </el-card>

    <!-- 底部操作模块：返回/保存 居中 -->
    <el-card class="section-card">
      <div class="op-bottom">
        <el-button size="large" @click="handleCancel">返回列表</el-button>
        <el-button size="large" type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.edit-wrap{ display:flex; flex-direction:column; gap:12px; }
.header-row{ display:flex; align-items:center; }
.title{ font-size:20px; font-weight:700; }
.spacer{ flex:1; }
.section-title{ text-align:center; color:#606266; }
.base-form{ margin-top:8px; }
.grid{ display:grid; grid-template-columns: 1fr 1fr; column-gap:24px; }
.col{ display:flex; flex-direction:column; gap:12px; }
.inline{ display:flex; align-items:center; }
.gap-8{ width:8px; }
.gap-12{ width:12px; }
.gap-24{ width:24px; }
.muted{ color:#909399; font-size:12px; }
.remark-item :deep(textarea){ min-height:84px; }

.image-row{ display:flex; gap:16px; }
.image-row .left{ display:flex; align-items:flex-start; gap:12px; }
.image-row .right{ flex:1; min-height:120px; background: #fff; border:1px dashed #e5e7eb; border-radius:6px; }

.attach-drag{ width:100%; }
.section-card :deep(.el-card__header){ text-align:center; }
.img-empty{ width:240px; height:160px; display:flex; align-items:center; justify-content:center; color:#999; background:#f8f9fb; border:1px dashed #e5e7eb; border-radius:6px; }
.file-line{ margin-top:8px; }
.op-bottom{ display:flex; justify-content:center; gap:16px; }
</style>
